package com.ruoyi.web.controller.combat.socialmedia;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.WeiboSendVo;
import com.ruoyi.combat.domain.FollowOrUnFollowVo;
import com.ruoyi.combat.domain.camera.CombatCameraInfo;
import com.ruoyi.combat.domain.userlocation.CombatRelation;
import com.ruoyi.combat.domain.userlocation.CombatUser;
import com.ruoyi.combat.mapper.userlocation.CombatBlogMapper;
import com.ruoyi.combat.service.socialmedia.CombatCrawlService;
import com.ruoyi.combat.service.userlocation.ICombatBlogService;
import com.ruoyi.combat.service.userlocation.ICombatRelationService;
import com.ruoyi.combat.service.userlocation.ICombatUserService;
import com.ruoyi.combat.util.weibo.WeiboApiUtil;
import com.ruoyi.combat.util.weibo.WeiboUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.file.service.ISysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户信息Controller
 *
 * @author ruoyi
 * @date 2024-08-30
 */
@Api(tags = "课题三、课题五：网络抗定位、抗关联-重保用户管理")
@RestController
@RequestMapping("/userlocation/user")
public class CombatUserController extends BaseController {
    @Autowired
    private ICombatUserService combatUserService;
    @Autowired
    private WeiboApiUtil weiboApiUtil;
    @Autowired
    private ISysFileService fileService;
    @Autowired
    private CombatCrawlService combatCrawlService;
    @Autowired
    private ICombatBlogService combatBlogService;
    @Autowired
    private ICombatRelationService  combatRelationService;
    @Autowired
    private WeiboUtil weiboUtil;
    /**
     * 查询用户信息列表
     */
    @ApiOperation(value = "查询用户信息列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(CombatUser combatUser) {
        startPage();
        List<CombatUser> list = combatUserService.selectCombatUserList(combatUser);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @ApiOperation(value = "导出用户信息列表")
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CombatUser combatUser) {
        List<CombatUser> list = combatUserService.selectCombatUserList(combatUser);
        ExcelUtil<CombatUser> util = new ExcelUtil<CombatUser>(CombatUser.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @ApiOperation(value = "获取用户信息详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(combatUserService.selectCombatUserById(id));
    }

    /**
     * 获取用户信息详细信息
     */
    @ApiOperation(value = "获取用户信息详细信息")
    @GetMapping(value = "/userId/{userId}")
    public AjaxResult getInfoByuserId(@PathVariable("userId") String userId) {
        return success(combatUserService.selectCombatUserByUserId(userId));
    }

    /**
     * 新增用户信息
     */
    @ApiOperation(value = "新增用户信息")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CombatUser combatUser) {
        CombatUser combatUser1 = new CombatUser();
        combatUser1.setUserId(combatUser.getUserId());
        List<CombatUser> combatUsers = combatUserService.selectCombatUserList(combatUser);
        if (combatUsers.size() > 0) {
            return AjaxResult.error("用户已存在");
        }
        return toAjax(combatUserService.insertCombatUser(combatUser));
    }

    /**
     * 修改用户信息
     */
    @ApiOperation(value = "修改用户信息")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CombatUser combatUser) {
        return toAjax(combatUserService.updateCombatUser(combatUser));
    }

    /**
     * 删除用户信息
     */
    @ApiOperation(value = "删除用户信息")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(combatUserService.deleteCombatUserByIds(ids));
    }

    @ApiOperation(value = "关注")
    @PostMapping("/tofollow")
    public AjaxResult tofollow(@RequestBody FollowOrUnFollowVo vo) {
        String userId = vo.getUserId();
        if (StringUtils.isNotEmpty(userId)) {
            CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
            if (combatUser != null) {
                if (combatUser.getToken() != null) {
                    weiboApiUtil.tofollow(userId, vo.getTargetUserIds());
                    return AjaxResult.success("关注成功");
                } else {
                    return AjaxResult.error("用户未授权");
                }
            } else {
                return AjaxResult.error("用户不存在");
            }
        } else {
            return AjaxResult.error("用户ID不能为空");
        }
    }
    @ApiOperation(value = "删除")
    @PostMapping("/todestroy")
    public AjaxResult todestroy(@RequestBody FollowOrUnFollowVo vo) {
        String userId = vo.getUserId();
        if (StringUtils.isNotEmpty(userId)) {
            CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
            if (combatUser != null) {
                if (combatUser.getToken() != null) {
                    weiboApiUtil.todestroy(combatUser.getToken(), vo.getTargetUserIds());
                    Long [] ids = vo.getTargetUserIds().stream().map(Long::valueOf).toArray(Long[]::new);
                    combatBlogService.deleteCombatBlogByIds(ids);
                    return AjaxResult.success("删除成功");
                } else {
                    return AjaxResult.error("用户未授权");
                }
            } else {
                return AjaxResult.error("用户不存在");
            }
        } else {
            return AjaxResult.error("用户ID不能为空");
        }
    }

    @ApiOperation("取消关注")
    @PostMapping("/unfollow")
    public AjaxResult unfollow(@RequestBody FollowOrUnFollowVo vo) {
        String userId = vo.getUserId();
        if (StringUtils.isNotEmpty(userId)) {
            CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
            if (combatUser != null) {
                if (combatUser.getToken() != null) {
                    weiboApiUtil.unfollow(userId, vo.getTargetUserIds());
                    List<String> targetUserIds = vo.getTargetUserIds();
                    for (String targetUserId : targetUserIds) {

                        CombatRelation combatRelation = new CombatRelation();
                        combatRelation.setUserid(userId);
                        combatRelation.setTargetid(targetUserId);
                        List<CombatRelation> combatRelations = combatRelationService.selectCombatRelationList(combatRelation);
                        for (CombatRelation relation : combatRelations) {
                            combatRelationService.deleteCombatRelationById(relation.getId());
                        }
                    }
                    return AjaxResult.success("取消关注成功");
                } else {
                    return AjaxResult.error("用户未授权");
                }
            } else {
                return AjaxResult.error("用户不存在");
            }
        } else {
            return AjaxResult.error("用户ID不能为空");
        }
    }

    @PostMapping("/sendWeiBo")
    public AjaxResult sendWeiBo(@RequestBody WeiboSendVo vo) {
        String userId = vo.getUserId();
        if (StringUtils.isNotEmpty(userId)) {
            CombatUser combatUser = combatUserService.selectCombatUserByUserId(userId);
            String token = combatUser.getToken();
            if (StringUtils.isNotEmpty(token)) {
                List<String> imgPathList = vo.getImgList();
                List<Map> fileList = new ArrayList<>();
                for (int i = 0; i < imgPathList.size(); i++) {
                    String s = imgPathList.get(i);
                    byte[] download = downloadPicture(s);
                    String s1 = s.split("\\.")[1];
                    s1 = i+"."+s1;
                    Map map = new HashMap<>();
                    map.put("fileData", download);
                    map.put("filename", s1);
                }

                String content = vo.getContent();
                String s = weiboUtil.send_weibo(userId, content, fileList);
//                String s = weiboApiUtil.sendContent(token, content, pic_id, IpUtils.getIpAddr());

                combatCrawlService.crawlWeiboByUserId(String.valueOf(combatUser.getId()));
            } else {
                return AjaxResult.error("用户未授权");
            }
        }
        return AjaxResult.success();

    }

     /**
     * 删除用户相关的所有博文 参数userId
     */
     @ApiOperation(value = "删除用户相关的所有博文")
     @GetMapping(value = "/deleteUserBlog/{userId}")
     public AjaxResult deleteUserBlog(@PathVariable("userId") String userId) {
         return success(combatBlogService.deleteCombatBlogByUserId(userId));
     }


    /**
     * 下载网络图片
     *
     * @param urlList 网络路径
     */
    public byte[] downloadPicture(String urlList) {
        urlList = encodeChineseInUrl(urlList);
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] byteArray = output.toByteArray();
            dataInputStream.close();
            return byteArray;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 导入重保用户
     */
    @ApiOperation(value = "导入重保用户")
    @Log(title = "导入重保用户", businessType = BusinessType.IMPORT)
    @PostMapping("/imports")
    public AjaxResult imports(MultipartFile file) throws IOException {
        ExcelUtil<CombatUser> util = new ExcelUtil<CombatUser>(CombatUser.class);
        List<CombatUser> userList = util.importExcel(file.getInputStream());
        String message = combatUserService.importUserInfo(userList);
        return success(message);
    }

    public static String encodeChineseInUrl(String url) {
        try {
            // 分割URL为协议、域名和路径部分
            int protocolEnd = url.indexOf("://");
            if (protocolEnd == -1) {
                return URLEncoder.encode(url, StandardCharsets.UTF_8.toString())
                        .replace("+", "%20");
            }

            String protocol = url.substring(0, protocolEnd + 3);
            String rest = url.substring(protocolEnd + 3);

            // 分割域名和路径
            int pathStart = rest.indexOf('/');
            if (pathStart == -1) {
                return protocol + rest; // 没有路径部分，无需编码
            }

            String domain = rest.substring(0, pathStart);
            String path = rest.substring(pathStart);

            // 只对路径部分编码
            String encodedPath = URLEncoder.encode(path, StandardCharsets.UTF_8.toString())
                    .replace("+", "%20")
                    .replace("%2F", "/") // 保留路径分隔符
                    .replace("%3A", ":")
                    .replace("%3F", "?")
                    .replace("%3D", "=")
                    .replace("%26", "&");

            return protocol + domain + encodedPath;
        } catch (Exception e) {
            return url; // 编码失败返回原URL
        }
    }


}
